<template>
    <el-tabs v-model="activeName" class="flexClass">
        <el-tab-pane label="开卡结账" name="first" style="height:100%;">
            <div class="mainDiv">
            <el-row style="height: 100%;">
                <el-col :span="12">
                    <el-form ref="form" label-width="70px">
                        <el-form-item label="支付信息" style="color: #606266">
                            <p style="margin:0px">
                                订单总计：{{(fenpeijine.zongji).toFixed(2)}} 元
                            </p>
                            <p style="margin:0px">
                                已支付：余额 + 赠送余额 = {{(fenpeijine.usebalance).toFixed(2)}} + {{(fenpeijine.usegiftbalance).toFixed(2)}} = {{(fenpeijine.kahao + fenpeijine.usebalance + fenpeijine.usegiftbalance).toFixed(2)}} 元
                            </p>
                            <p style="margin:0px">
                                应支付：现金支付 = {{(fenpeijine.usemoney).toFixed(2)}} 元
                            </p>
                        </el-form-item>
                        <el-form-item label="付款方式">
                            <template v-if="order.status == 0">
                                <el-button icon="plus" type="primary" size="small" @click="addRow(payListRef)">加一行</el-button>
                            </template>
                            <el-table :data="paylist" height="300">
                                <el-table-column prop="accountname" label="收款账户" :show-overflow-tooltip="showOwer">
                                    <template slot-scope="scope">
                                        <el-input :ref="makeIndex(scope.$index, 1, payListRef)" @focus="setIndex(scope.$index, 1, payListRef)" @blur="blurcheck($event, scope.row.accountname)" @keyup.enter.native="searchAccount($event, scope)" :value="scope.row.accountname" size="small" v-if="order.status == 0">
                                            <i slot="suffix" class="el-icon-search" style="line-height: 32px;width: 25px;cursor: pointer;" @click="firstPopupAccount(scope)"></i>
                                        </el-input>
                                        <span v-else>{{scope.row.accountname}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="type" label="收款方式" width="98">
                                    <template slot-scope="scope">
                                        <el-tag size="mini" type="success" v-if="scope.row.type == 1">现金支付</el-tag>
                                        <el-tag size="mini" type="primary" v-else-if="scope.row.type == 2">可用余额</el-tag>
                                        <el-tag size="mini" type="primary" v-else>赠送余额</el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="paymoney" label="收款金额">
                                    <template slot-scope="scope">
                                        <el-input placeholder="元" :ref="makeIndex(scope.$index, 2, payListRef)" @focus="setIndex(scope.$index, 2, payListRef)" v-model="scope.row.paymoney" @keyup.enter.native="nextInput(payListRef)" size="small" v-if="order.status == 0">
                                        </el-input>
                                        <span v-else>{{scope.row.paymoney}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="" label="操作" width="80" v-if="order.status == 0">
                                    <template slot-scope="scope">
                                        <el-button type="danger" size="mini" @click="deleterow(scope.$index, paylist)" v-show="scope.row.type == 1">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <el-row>
                                <el-col :span="24" style="text-align:right">
                                    <span style="background-color:#f3b5b5;border-radius:3px;color:#fff;padding:3px;" v-if="yingshoujine != 0">应收现金：{{yingshoujine}}元</span>
                                </el-col>
                            </el-row>
                        </el-form-item>
                    </el-form>
                </el-col>
                <el-col :span="12">
                    现金业绩
                    <el-form ref="form" label-width="80px">
                        <el-form-item label="分配业绩" v-show="fenpeijine.usemoney > 0 || fenpeijine.qikahao > 0">
                            <el-button icon="plus" type="primary" size="small" @click="addRow(yejiListRef)">加一行</el-button>
                            <el-button style="float:right;" type="primary" size="small" icon="upload2" v-if="order.status != 0" @click="chongxinfenpei">重新分配</el-button>
                            <el-table :data="yejilist" max-height="250">
                                <el-table-column prop="username" label="姓名">
                                    <template slot-scope="scope">
                                        <el-input :ref="makeIndex(scope.$index, 1, yejiListRef)" @focus="setIndex(scope.$index, 1, yejiListRef)" @blur="blurcheck($event, scope.row.username)" @keyup.enter.native="searchUser($event, scope.row)" :value="scope.row.username" size="small">
                                            <i slot="suffix" class="el-icon-search" style="line-height: 32px;width: 25px;cursor: pointer;" @click="firstPopupUser(scope)"></i>
                                        </el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="fuwutype" label="属性" width="98">
                                    <template slot-scope="scope">
                                        <el-input :ref="makeIndex(scope.$index, 2, yejiListRef)" @focus="setIndex(scope.$index, 2, yejiListRef)" :value="returnValue(scope)" @blur="checkValue($event, scope)" size="small" @keyup.enter.native="selectFuwuType($event, scope)"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="xianjinyeji" label="现金业绩">
                                    <template slot-scope="scope">
                                        <el-input :ref="makeIndex(scope.$index, 3, yejiListRef)" @focus="setIndex(scope.$index, 3, yejiListRef)" v-model="scope.row.xianjinyeji" size="small" @keyup.enter.native="nextInput(yejiListRef)">
                                        </el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="kahaoyeji" label="卡耗业绩">
                                    <template slot-scope="scope">
                                        <el-input :ref="makeIndex(scope.$index, 4, yejiListRef)" @focus="setIndex(scope.$index, 4, yejiListRef)" v-model="scope.row.kahaoyeji" size="small" @keyup.enter.native="nextInput(yejiListRef)">
                                        </el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="" label="操作" width="80">
                                    <template slot-scope="scope">
                                        <el-button type="danger" size="mini" @click="deleterow(scope.$index, yejilist)">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <el-row>
                                <el-col :span="24" style="text-align:right">
                                    <span style="background-color:#f3b5b5;border-radius:3px;color:#fff;padding:3px" v-show="yingfenyeji.yingfenxianjin != 0">现金差：{{yingfenyeji.yingfenxianjin}}元</span>
                                    <span style="background-color:#f3b5b5;border-radius:3px;color:#fff;padding:3px" v-show="yingfenyeji.yingfenkahao != 0">卡耗差：{{yingfenyeji.yingfenkahao}}元</span>
                                </el-col>
                            </el-row>
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>
            <div style="padding: 10px">
                <el-button type="danger" class="fr" style="float: left;" @click="goto(0)">编辑订单</el-button>
                <el-button style="float:right;" type="primary" @click="goto(2)">下一步</el-button>
                <el-button icon="check" type="success" style="float: right" @click="submit" v-if="order.status == 0" v-qx="quanxian.jiezhang">确定结账</el-button>
                <el-button icon="check" type="warning" style="float: right" @click="fanjiezhang" v-else v-qx="quanxian.fanjiezhang">反结账</el-button>
            </div>
            </div>
        </el-tab-pane>
        <el-tab-pane label="订单详情" name="second">
            <orderInfo :order="order"></orderInfo>
        </el-tab-pane>
    </el-tabs>
</template>
<script>
import C from '@/common/common.js'
import D from '@/service/common/datas.js'
import keyUpRef from '@/service/shop/keyupref.js'
import S from '@/service/shop/search.js'
import P from '@/service/shop/popup.js'
import orderInfo from './orderInfo.vue'

export default {
  name: 'addOpenCard',
  props: ['order', 'paylist', 'yejilist'],
  data () {
    return {
      // 杂项
      showOwer: true,
      activeName: 'first',
      payListRef: D.payListRef,
      yejiListRef: D.yejiListRef,
      quanxian: {
        add: 'opencards_add',
        jiezhang: 'opencards_jiezhang',
        fanjiezhang: 'opencards_fan',
        dayin: 'opencards_print',
        fenpei: 'opencards_fen',
        fanfenpei: 'opencards_fanfen',
        chongxinfenpei: 'opencards_chongxin'
      }
    }
  },
  methods: C.assign(keyUpRef, {
    returnValue (scope) {
      if (scope.column.property == 'rowtype') {
        return scope.row[scope.column.property] == 1 ? '产品' : scope.row[scope.column.property] == 2 ? '项目' : '卡项'
      } else if (scope.column.property == 'fuwutype') {
        return scope.row[scope.column.property] == 1 ? '点客' : '轮牌'
      } else {
        return scope.row[scope.column.property] == 1 ? '是' : '否'
      }
    },
    checkValue (e, scope) {
      e.target.value = this.returnValue(scope)
    },
    selectFuwuType (e, scope) {
      let v = e.target.value
      let isHave = false
      D.fuwuType.forEach((row) => {
        if (row.name == v || row.value == v) {
          isHave = true
          scope.row[scope.column.property] = row.value
          e.target.value = row.name
          // 如果是赠送赋值为零
          this.nextInput(this.yejiListRef)
        }
      })
      if (!isHave) {
        C.error('请输入0或1进行选择！')
        e.target.select()
      }
    },
    blurcheck: function (e, value) {
      e.target.value = value
    },
    async searchAccount (e, scope) {
      if (!C.openLoading()) return false
      let data = await S.searchAccount({ keywords: e.target.value })
      data = data.list.length == 1
        ? data.list[0]
        : await P.accountPopup({ keywords: e.target.value }, data)
      C.closeLoading()

      if (data.id) {
        // 判断是否重复
        let key = C.inarray({ accountid: data.id }, this.paylist)
        if (key == -1) {
          scope.row.accountid = data.id
          scope.row.accountname = data.name
          this.nextInput(this.payListRef)
        } else if (scope.$index == key) {
          this.nextInput(this.payListRef)
        } else {
          C.error('选择账户重复！')
          e.target.select()
          return false
        }
      }
    },
    async firstPopupAccount (scope) {
      this.setIndex(scope.$index, 1, this.payListRef)
      let data = await P.accountPopup({ keywords: '' })
      if (data && data.id) {
        // 判断是否重复
        let key = C.inarray({ accountid: data.id }, this.paylist)
        if (key == -1) {
          scope.row.accountid = data.id
          scope.row.accountname = data.name
          this.nextInput(this.payListRef)
        } else if (scope.$index == key) {
          this.nextInput(this.payListRef)
        } else {
          C.error('选择账户重复！')
          // e.target.select()
          return false
        }
      }
    },
    async searchUser (e, row) {
      if (!C.openLoading()) return false
      let filter = { keywords: e.target.value, guestid: this.order.ginfo.id }
      let data = await S.searchUser(filter)
      data = data.list.length == 1
        ? data.list[0]
        : await P.userPopup(filter, data)
      C.closeLoading()
      if (data.id) {
        // 判断是否重复
        let key = C.inarray({ userid: data.id }, this.yejilist)
        if (key == -1) {
          row.userid = data.id
          row.username = data.name
          row.bumenid = data.bumenid
          row.xiaozuid = data.xiaozuid
          this.nextInput(this.yejiListRef)
        } else {
          C.error('选择员工重复！')
          e.target.select()
          return false
        }
      }
    },
    async firstPopupUser (scope) {
      this.setIndex(scope.$index, 1, this.yejiListRef)
      let data = await P.userPopup({ keywords: '', guestid: this.order.ginfo.id })
      if (data && data.id) {
        // 判断是否重复
        let key = C.inarray({ userid: data.id }, this.yejilist)
        if (key == -1) {
          scope.row.userid = data.id
          scope.row.username = data.name
          scope.row.bumenid = data.bumenid
          scope.row.xiaozuid = data.xiaozuid
          this.nextInput(this.yejiListRef)
        } else if (scope.$index == key) {
          this.nextInput(this.yejiListRef)
        } else {
          C.error('选择员工重复！')
          // e.target.select()
          return false
        }
      }
    },
    deleterow: C.deleterow,
    submit: async function () {
      // 判断是否有未分配的业绩和收款金额
      if (this.yingshoujine != 0) {
        C.error('应收现金不正确！')
        return false
      }

      if (this.yingfenyeji.yingfenxianjin != 0 || this.yingfenyeji.yingfenkahao != 0) {
        C.error('分配业绩金额不正确！')
        return false
      }

      // 判断收款账户和现金业绩
      let err = false
      let isqian = false
      this.paylist.forEach((row) => {
        if (!row.accountid || row.accountid <= 0) {
          C.error('收款账户填写不正确！')
          err = true
        }
        if (row.paymoney <= 0) {
          C.error('收款金额填写不正确！')
          err = true
        }
      })
      if (this.yejilist.length) {
        for (var i = 0, xjlen = this.yejilist.length; i < xjlen; i++) {
          if (!this.yejilist[i].userid || this.yejilist[i].userid <= 0) {
            C.error('员工信息填写不正确！')
            return false
          }
          if (this.yejilist[i].xianjinyeji <= 0 && this.yejilist[i].kahaoyeji <= 0 || this.yejilist[i].xianjinyeji < 0 || this.yejilist[i].kahaoyeji < 0) {
            C.error(this.yejilist[i].username + '[员工]分配业绩不正确！')
            return false
          }
        }
      }
      if (this.order.ginfo.balance - this.fenpeijine.usebalance < 0) isqian = true
      if (this.order.ginfo.giftbalance - this.fenpeijine.usegiftbalance < 0) {
        C.error('赠送余额不足！')
        return false
      }
      let initConfig = JSON.parse(C.getLocalStorage('initConfig'))
      if (err) return false
      if (isqian && !initConfig.isqian) {
        C.error('该客户账户余额不足！')
        return false
      }
      if (isqian && !confirm('该客户余额已不足，会产生欠款，确定要继续吗？')) return false

      let data = {
        order: this.order,
        paylist: this.paylist,
        yejilist: this.yejilist
      }
      let res = await C.ajax('/shop/card/opencardjiezhang', { data: JSON.stringify(data) }, 'post')
      if (res) {
        C.success(res.data)
        this.$emit('goto', {index: 2, status: 1})
      }
    },
    chongxinfenpei: async function () {
      if (this.yingfenyeji.yingfenxianjin != 0 || this.yingfenyeji.yingfenkahao != 0) {
        C.error('分配业绩金额不正确！')
        return false
      }
      if (this.yejilist.length) {
        for (var i = 0, xjlen = this.yejilist.length; i < xjlen; i++) {
          if (this.yejilist[i].xianjinyeji <= 0 && this.yejilist[i].kahaoyeji <= 0 || this.yejilist[i].xianjinyeji < 0 || this.yejilist[i].kahaoyeji < 0) {
            C.error(this.yejilist[i].username + '[员工]分配业绩不正确！')
            return false
          }
        }
      }
      let data = {
        order: this.order,
        yejilist: this.yejilist
      }
      // return false
      let res = await C.ajax('/shop/card/resertallot', { data: JSON.stringify(data) }, 'post')
      if (res) {
        C.success(res.data.info)
      }
    },
    fanjiezhang: function () {
      C.confirm('此操作将清除已结账的信息, 是否继续?', async () => {
        let res = await C.ajax('/shop/card/unpay', { id: this.order.id }, 'post')
        if (res) {
          C.success(res.data)
          this.$emit('goto', {index: 1, status: 0})
        }
      })
    },
    goto (index) {
      this.$emit('goto', {index: index})
    }
  }),
  computed: {
    shishouxianjin: function () {
      let m = 0
      this.paylist.forEach((row) => {
        m += Number(row.paymoney)
      })
      return m.toFixed(2)
    },
    yingshoujine: function () {
      return parseFloat(this.fenpeijine.usemoney - this.shishouxianjin).toFixed(2)
    },
    yingfenyeji: function () {
      let o = {}
      o.yingfenxianjin = (this.fenpeijine.usemoney - this.shifenyeji.shifenxianjin).toFixed(2)
      o.yingfenkahao = (this.fenpeijine.qikahao - this.shifenyeji.shifenkahao).toFixed(2)
      return o
    },
    shifenyeji: function () {
      let o = { shifenxianjin: 0, shifenkahao: 0 }
      if (this.yejilist.length > 0) {
        this.yejilist.forEach((row) => {
          o.shifenxianjin += Number(row.xianjinyeji)
          o.shifenkahao += Number(row.kahaoyeji)
        })
      }
      return o
    },
    fenpeijine: function () {
      let o = { putong: 0, kahao: 0, qikahao: 0, zancun: 0, zongji: 0, usemoney: 0, usebalance: 0, usegiftbalance: 0, usecard: 0 }
      this.order.orderlist.forEach((row) => {
        if (row.consumetype == 1) {
          o.putong += Number(row.amount)
          if (row.cardtype == 1) {
            o.qikahao += Number(row.usebalance) + Number(row.usegiftbalance)
          }
        } else if (row.consumetype == 2) {
          o.kahao += Number(row.amount)
        } else {
          o.zancun += Number(row.amount)
        }
        o.zongji += Number(row.amount)

        o.usemoney += Number(row.usemoney)
        o.usebalance += Number(row.usebalance)
        o.usegiftbalance += Number(row.usegiftbalance)
        o.usecard = 0
      })
      return o
    }
  },
  mounted: async function () {
  },
  components: { orderInfo }
}
</script>
<style>
.flexClass {
    height: 100%;
    position: relative;
    display: flex;
    flex-direction: column;
}

.el-tabs__content {
    height: 100%;
}
</style>